<?php
/**
 * Created by PhpStorm.
 * User: xiaoda
 * Date: 2017/4/13
 * Time: 11:06
 */

namespace App\Console\Commands;

use App\Console\Base;
use App\Models\Agent;
use App\Models\Answer;
use App\Models\BankReceiveAccount;
use App\Models\Level;
use App\Models\MoneyDeposit;
use App\Models\PayVendorScene;
use App\Models\Profile;
use App\Services\MoneyDepositService;
use App\Services\RpcService;
use common\enum\BankReceiveAccountEnum;
use common\enum\PayVendorSceneEnum;
use common\services\UserLogsService;
use common\enum\MoneyDepositEnum;
use common\utils\RedisKeys;
use common\utils\SysCode;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;


class PaymentProcessor extends Base
{

    /**
     * 控制台命令 signature 的名称。
     *
     * @var string
     */
    protected $signature = self::PREFIX . 'payment';

    /**
     * 控制台命令说明。
     *
     * @var string
     */
    protected $description = 'Payment';

    public function handle()
    {
        //过期订单修改失败
        $this->autoSetFailed();

        //自动补单
        $this->autoSupplement();

        //暂停支付渠道自动启用
        $this->autoPutOn();
    }

    private function autoSetFailed()
    {
        $time = date('Y-m-d H:i:s', time() - 60 * 30);
        try {
            //查询半小时以前待支付订单， 状态改为失败
            $this->info("查询半小时以前待支付订单， 状态改为失败");
            //先查询所有的半小时以前待支付订单
            $onlinePendingOrderList = MoneyDeposit::where('recharge_time', '<', $time)
                ->where(['status' => MoneyDepositEnum::STATUS_PENDING])
                ->where(['is_online' => MoneyDepositEnum::IS_ONLINE_TRUE])->get();
            if (count($onlinePendingOrderList) == 0) {
                return;
//            return $this->info("半小时以前无在线待支付订单");
            }
            $onlinePendingOrderList = $onlinePendingOrderList->toArray();
            foreach ($onlinePendingOrderList as $pendingOrder) {
                //修改状态失败
                if (!MoneyDeposit::where(['id' => $pendingOrder['id']])->update(['status' => MoneyDepositEnum::STATUS_FAILED])) {
                    $this->info("订单：{$pendingOrder['order_number']} 修改状态失败");
                    continue;
                }
                //修改 累计支付渠道的日累计， 总累计金额
                if (!MoneyDepositService::handleOnlineDepositLimitAmount($pendingOrder['online_pay_id'],
                    -abs($pendingOrder['amount']))) {
                    $this->info("订单：{$pendingOrder['order_number']} 修正累计支付渠道的日累计，总累计金额 失败");
                    continue;
                }
            }
        } catch (\Throwable $e) {
            $this->error("过期订单修改失败异常：" . $e->getMessage());
        }
    }

    private function autoSupplement()
    {
        $time = date('Y-m-d H:i:s', time() - 60 * 30);
        //自动补单
        try {
            //查询半小时内的在线支付订单， 进行自动补单
            $this->info("查询半小时内的在线支付订单， 进行自动补单开始");
            $onlinePendingOrderList = MoneyDeposit::where('recharge_time', '>', $time)
                ->where(['status' => MoneyDepositEnum::STATUS_PENDING])
                ->where(['is_online' => MoneyDepositEnum::IS_ONLINE_TRUE])
                ->get();
            if (count($onlinePendingOrderList) == 0) {
                return;
//            return $this->error("半小时内无在线待支付订单");
            }
            $onlinePendingOrderList = $onlinePendingOrderList->toArray();
            foreach ($onlinePendingOrderList as $pendingOrder) {
                $orderNumber = $pendingOrder['order_number'];
                $data = [
                    'order_number' => $orderNumber
                ];
                $ret = RpcService::rpcRequest('/payment/supplementOrder', 'POST', $data);
                if (isset($ret['code']) && $ret['code'] == 0) {
                    $this->info("订单：" . $orderNumber . ' 补单成功');
                } else {
                    $this->error("订单：" . $orderNumber . ' 补单失败' . ($ret['msg'] ?? ''));
                }
            }
            $this->info("查询半小时内的在线支付订单， 进行自动补单结束");
        } catch (\Throwable $e) {
            $this->error("自动补单异常：" . $e->getMessage());
        }
    }

    private function autoPutOn()
    {
        //暂停支付渠道自动启用 (线上 pay_vendor_scene ？  线下 bank_receive_account)
        try {
            //公司入款账户
            $pausedBankReceiveAccount = BankReceiveAccount::where(['status' => BankReceiveAccountEnum::STATUS_PAUSE])->get();
            if (!empty($pausedBankReceiveAccount)) {
                foreach ($pausedBankReceiveAccount as $val) {
                    if ($val['total_amount'] < $val['total_max_limit'] && $val['day_amount'] < $val['day_max_limit']) {
                        if (!BankReceiveAccount::where(['id' => $val['id']])->update(['status' => BankReceiveAccountEnum::STATUS_ON])) {
                            $this->error("收款账号：" . $val['id'] . ' 自动启用失败');
                        }
                    }
                }
            }
            //在线支付渠道
            $pausedPayVendorScene = PayVendorScene::where(['status' => PayVendorSceneEnum::STATUS_PAUSE])->get();
            if (!empty($pausedPayVendorScene)) {
                foreach ($pausedPayVendorScene as $val) {
                    if ($val['total_amount'] < $val['total_max_limit'] && $val['day_amount'] < $val['day_max_limit']) {
                        if (!PayVendorScene::where(['id' => $val['id']])->update(['status' => PayVendorSceneEnum::STATUS_ON])) {
                            $this->error("支付渠道：" . $val['id'] . ' 自动启用失败');
                        }
                    }
                }
            }
        } catch (\Throwable $e) {
            $this->error("暂停支付渠道自动启用异常：" . $e->getMessage());
        }
    }


}